//
//  XFMainTabBar.swift
//  SinaBlog
//
//  Created by macs on 15/11/8.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

import UIKit

class MainTabBar: UITabBar {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    //重写了init(frame: CGRect),默认就是代码创建
    required init?(coder aDecoder: NSCoder) {
        //这个方法中只有默认报错的语句
        //如果有调用者通过 sb / xib创建了该对象 这个时候程序就崩溃
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setUpUI()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //修改自己的tabbarItem的位置
        let w = self.bounds.width / 5
        let h = self.bounds.height
        //预先设置一个 rect, 通过 rect 来修改 item 的属性
        let rect = CGRect(x: 0, y: 0, width: w, height: h)
        var index :CGFloat = 0
        
        for subview in subviews {
            //判断是否是系统的tabbarButton
            
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!){
                subview.frame = CGRectOffset(rect, w * index, 0)
                //                if index == 1 {
                //                    index++
                //                }
                //            index++
                index += index == 1 ? 2 : 1
            }
        }
        //设置自己创建的 button 的 frame
        compBtn.frame = CGRectOffset(rect, w * 2, 0)
        //compBtn.center.y = -5
        bringSubviewToFront(compBtn)
    }
    
   private func setUpUI() {
        
        addSubview(compBtn)
        
    }
    
    lazy var compBtn : UIButton = {
        
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.sizeToFit()
        return btn
    } ()
    
}
